{% extends 'basic/layout/page_basic_bread_query.html' %}
{% load static %}

<!-- Title -->
{% block title %} 角色管理 {% endblock %}

<!-- CSS -->
{% block css %} {% endblock %}


<!-- Bread -->
{% block breadsecond %} 用户角色 {% endblock %}
{% block breadthird %} 角色管理 {% endblock %}

<!-- Content -->
{% block excontent %}
    <!-- 内容01：面包屑导航 -->
    <!-- 内容02：查询 -->
    <!-- 内容03: 表格部分 -->
    <table class="layui-hide" id="tableArea" lay-filter="tableArea"></table>

    <!-- 内容04：表格右侧的操作按钮 -->
    <script type="text/html" id="tableButton">
        <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="edit">
            <i class="fa fa-edit" aria-label="true"></i>&nbsp;编辑
        </a>
        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">
            <i class="fa fa-trash" aria-label="true"></i>&nbsp;删除
        </a>
        <a class="layui-btn layui-btn-warm layui-btn-xs" lay-event="permission">
            <i class="fa fa-key" aria-label="true"></i>&nbsp;分配权限
        </a>
    </script>

    <!-- 内容05：添加和修改的弹出层 -->
    <div id="layerArea" style="display: none; padding: 30px;">
        <form id="layerForm" class="layui-form" lay-filter="layerForm">
            {% csrf_token %}

            <div class="layui-form-item">
                <div class="layui-inline" style="display: none">
                    <label class="layui-form-label" for="id"><b> 编号：</b></label>
                    <div class="layui-input-inline">
                        <input type="text" name="id" id="id" class="layui-input">
                        <span class="error_msg" style="color:red; position: absolute"></span>
                    </div>
                </div>
                <div class="layui-inline">
                    <label class="layui-form-label" for="name"><b> 角色名称：</b></label>
                    <div class="layui-input-inline">
                        <input type="text" name="name" id="name" class="layui-input">
                        <span class="error_msg" style="color:red; position: absolute"></span>
                    </div>
                </div>

            </div>
            <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label" for="desc"><b> 角色描述：</b></label>
                    <div class="layui-input-inline">
                        <textarea type="text" id="desc" name="desc" class="layui-textarea"></textarea>
                        <span class="error_msg" style="color:red; position: absolute"></span>
                    </div>
                </div>
            </div>

            <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label" for="create_time"><b> 创建时间：</b></label>
                    <div class="layui-input-inline">
                        <input type="text" id="create_time" name="create_time" class="layui-input"
                               style="background-color:#eaeaea">
                    </div>
                </div>

            </div>
            <div class="layui-form-item">

                <div class="layui-inline">
                    <label class="layui-form-label" for="edit_time"><b> 修改时间：</b></label>
                    <div class="layui-input-inline">
                        <input type="text" id="edit_time" name="edit_time" class="layui-input"
                               style="background-color:#eaeaea">
                    </div>
                </div>
            </div>
        </form>
    </div>


    <!-- 内容06：分配权限的弹出层 -->
    <div id="permissionArea" class="demo-tree demo-tree-box" style="padding: 20px; display: none"></div>
{% endblock %}


<!-- JS -->
{% block js %}
    <script>
        let Operation = 0;  // 1-- 添加  2--修改
        // 入口函数
        $(function () {
            // === 初始化页面 ===
            //initPage();
            // === 初始化表格 ===
            initTable();
            // === 按钮点击 ===
            buttonClick();

        });


        // ============ 初始化表格的功能实现 ================
        function initTable() {
            layui.use(['table', 'form'], function () {
                let table = layui.table;
                let form = layui.form;

                // ===渲染表格===
                table.render({
                    elem: $('#tableArea')
                    , url: "{% url 'list_role' %}"
                    , method: 'post'
                    , where: {
                        // 携带输入的查询条件！
                        inputStr: $('#inputStr').val().trim(),
                        // q_experiment: $('#q_experiment').val().trim(),
                        csrfmiddlewaretoken: "{{ csrf_token }}",
                    }
                    , even: true
                    , cols: [[
                        {type: 'numbers', width: 60, title: '序号', align: 'center', sort: true}
                        , {field: 'name', width: 200, title: '角色名称', align: 'center', sort: true}
                        , {field: 'desc', title: '角色描述', align: 'center',}
                        , {fixed: 'right', title: '操作', width: 260, align: 'center', toolbar: '#tableButton'}
                    ]]
                    , page: true  // 启用分页，默认就向后台发送两个参数：page=1,limit=10
                    , limit: 15
                    , limits: [12, 15, 18, 20, 30, 50, 75, 100]
                    , done: function (res, current, count) {
                        $('thead tr').css({'background-color': '#009688', 'color': 'white'})
                    }

                });

                // ===侦听表格的按钮点击===
                table.on('tool(tableArea)', function (obj) {
                    // 取出当前行数据
                    let oneLineData = obj.data;
                    // 响应按钮的点击事件
                    if (obj.event === 'edit') {
                        // 修改Operation
                        Operation = 2;
                        // 点击编辑按钮的代码
                        loadLayer("修改【角色信息】", oneLineData);

                    } else if (obj.event === 'del') {
                        // 点击删除按钮的代码
                        deleteValue(oneLineData);

                    } else if (obj.event === 'permission') {

                        loadPermissionLayer(oneLineData)
                    }
                })
            })

        }

        // ============ 按钮点击的实现  ====================
        function buttonClick() {
            // === 添加按钮 ===
            $('#btnQuery').on('click', function () {
                initTable();
            });
            // === 显示全部 ===
            $('#btnAll').on('click', function () {
                location.reload();
            });
            // === 添加 ===
            $('#btnAdd').on('click', function () {
                // 修改Operation的值
                Operation = 1;
                loadLayer("添加【角色信息】");
            });
        }

        // ============ 展示弹出层 =========================
        function loadLayer(title, value = "") {

            // 展示弹出层的内容
            layui.use(['layer', 'form'], function () {
                let layer = layui.layer;
                let form = layui.form;

                layer.open({
                    type: 1,
                    title: "<b style='color:navy'>" + title + "</b>",
                    area: ['400px', '500px'],
                    offset: '30px',
                    btn: ['确定', '取消'],
                    content: $('#layerArea'),
                    resize: false,

                    // ===================== 三个回调函数 =====================
                    success: function (index, layero) {
                        // === 为非下拉框赋值 ====
                        form.val('layerForm', value);
                        form.render();

                        // 创建日期和修改日期只读
                        $('#layerForm').find('#create_time, #edit_time').prop('readonly', true);
                    },
                    yes: function (index, layero) {

                        // 清除表单的错误提示
                        $('.error_msg').empty();
                        // 表单的验证
                        if (!checkLayerForm()) {
                            return;
                        }
                        // 准备提交的URL
                        let commitURL = "{% url 'add_role' %}";
                        if (Operation === 2) {
                            commitURL = "{% url 'edit_role' %}";
                        }
                        // 使用Ajax提交
                        $.ajax({
                            url: commitURL,
                            method: 'post',
                            data: $('#layerForm').serialize(),
                            dataType: 'json',
                            success: function (res) {
                                if (res.status) {
                                    location.reload();
                                } else {
                                    layer.msg(res.error, {
                                        icon: 2,
                                        area: ['300px', '150px'],
                                        time: -1,
                                        btn: ['关闭']
                                    })
                                }
                            }
                        })
                    },
                    end: function (index, layero) {
                        // ==== 清空所有的表单值 ===
                        form.val('layerForm', {
                            id: "",
                            name: "",
                            desc: "",
                            create_time: "",
                            edit_time: "",
                        });

                        // 清除表单的错误提示
                        $('.error_msg').empty();
                    },

                })
            })
        }

        // ============ 展示添加或修改权限的弹出层 ===============
        function loadPermissionLayer(value) {

            // 定义变量
            let allPermission = "";
            let rolePermisson = "";
            let initPermission = [];
            let commitPermission = [];

            layui.use(['tree', 'layer'], function () {
                let tree = layui.tree;
                let layer = layui.layer;

                layer.open({
                    type: 1,
                    area: ['500px', '700px'],
                    title: "<b style='color:navy'>【" + value.name + "-设置权限】</b>",
                    content: $('#permissionArea'),
                    btn: ['确定', '取消'],

                    // success回调函数：弹出层展示的时候执行
                    success: function (index, layero) {

                        // 获取所有权限的树状结构
                        $.ajax({
                            url: "{% url 'list_permission' %}",
                            method: 'get',
                            dataType: 'json',
                            async: false,
                            success: function (res) {
                                allPermission = res.data;
                            }
                        });

                        // 获取当前角色具备的权限
                        $.ajax({
                            url: "{% url 'role_permission' %}",
                            method: 'post',
                            data: {
                                role_id: value.id,
                                csrfmiddlewaretoken: "{{ csrf_token }}",
                            },
                            dataType: 'json',
                            async: false,
                            success: function (res) {
                                rolePermisson = res.data;
                            }
                        });

                        // 在树状结构中选中当前的权限
                        $.each(allPermission, (index, value) => {
                            $.each(value.children, (i, v) => {
                                if (rolePermisson.indexOf(v.id) != -1) {
                                    v['checked'] = true;
                                }
                            })
                        });

                        // 展示在树状结构
                        loadTreePremission(allPermission);


                        // 获取当前角色的初始权限 -- 权限1
                        initPermission = tree.getChecked('demoid')


                    },
                    yes: function (index, layero) {
                        // 获取当前角色的初始权限 -- 权限2
                        commitPermission = tree.getChecked('demoid');
                        // 提取初识权限和提交权限
                        let initPermissionList = getPermissionDetail(initPermission);
                        let commitPermissionList = getPermissionDetail(commitPermission);

                        // 比较差异
                        let addPermissionList = [];   // 需要添加的权限   commitPermissionList - initPermissionList
                        let removePermissionList = []; //需要减少的权限   initPermissionList  -  commitPermissionList

                        // 获取要新建的权限
                        $.each(commitPermissionList, (index,value)=>{
                            if(initPermissionList.indexOf(value) === -1){
                                addPermissionList.push(value);
                            }
                        });
                        // 获取要删除的选线
                         $.each(initPermissionList, (index,value)=>{
                            if(commitPermissionList.indexOf(value) === -1){
                                removePermissionList.push(value);
                            }
                        });

                        // ============== 提交到后台 ============
                        $.ajax({
                            url:"{% url 'role_update_permission' %}",
                            method:'post',
                            data: {
                                role:value.id ,
                                add:JSON.stringify(addPermissionList),
                                remove: JSON.stringify(removePermissionList),
                                csrfmiddlewaretoken: "{{ csrf_token }}"
                            },
                            dataType:'json',
                            success: function (res) {
                                if(res.status){
                                    location.reload();
                                } else {
                                    layer.msg(res.error,{
                                        type:2,
                                        area: ['500px','250px'],
                                        time:-1,
                                        btn: ['关闭']
                                    })
                                }
                            }
                        })


                    },
                    end: function (index, layero) {

                    }

                })
            })

        }


        // ===============初始化弹出层树状权限======================
        function loadTreePremission(data) {
            layui.use(['tree'], function () {
                let tree = layui.tree;


                tree.render({
                    elem: '#permissionArea',
                    showCheckbox: true,
                    spread: false,
                    isJump: true,
                    data: data,
                    id: 'demoid',

                });
            })
        }

        // ============== 获取具体的权限条目 ======================
        function getPermissionDetail(perArray) {
            // 定义一个集合
            let Array01 = [];
            // 开始遍历
            $.each(perArray, (index, value)=>{
                $.each(value.children, (i, v)=>{
                    Array01.push(v.id);
                })
            });
            // 返回
            return Array01;
        }

        // ============= 对弹出层表单进行校验 =====================
        function checkLayerForm() {
            // 清除所有的错误
            $('.error_msg').empty();
            // 定义返回值
            let result = true;
            // 判断合同信息是否选择
            if ($('#name').val().trim().length === 0) {
                result = false;
                $('#name').next().text("角色名称不能为空！");
            }

            // 判断角色名称是否存在
            if (Operation === 1) {
                $.ajax({
                    url: "{% url 'role_exists_name' %}", //判断role是否存在
                    method: 'post',
                    data: {
                        name: $('#name').val().trim(),
                        csrfmiddlewaretoken: "{{ csrf_token }}"
                    },
                    dataType: 'json',
                    async: false,
                    success: function (res) {
                        if (res.status) {
                            result = false;
                            $('#name').next().text("角色名称已存在！");
                        }
                    }
                });
            }


            return result

        }


        //============= 删除计划信息 =========================
        function deleteValue(value) {
            console.log(value);
            //确认的提示
            let confirmStr = "您确认删除角色信息【" + value.name + "】信息吗？";
            // 确认
            layui.use('layer', function () {
                layer.confirm(confirmStr, {icon: 3, area: ['450px', '200px']}, function (index) {
                    // ajax
                    $.ajax({
                        url: "{% url 'del_role' %}",
                        method: "post",
                        data: {
                            id: value.id,
                            csrfmiddlewaretoken: "{{ csrf_token }}"
                        },
                        dataType: 'json',
                        success: function (res) {
                            if (res.status) {
                                location.reload();
                            } else {
                                layer.msg(res.error, {
                                    icon: 2,
                                    area: ['500px', '250px'],
                                    time: -1,
                                    btn: ['关闭']
                                });
                            }
                        }
                    })
                })
            })
        }


    </script>
{% endblock %}
